package com.gec.anan.common.login;


import com.gec.anan.common.constant.RedisConstant;
import com.gec.anan.common.execption.AnanException;
import com.gec.anan.common.result.ResultCodeEnum;
import com.gec.anan.common.util.AuthContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.bouncycastle.jce.provider.AnnotatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class LoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    //定义通知
    @Around("execution(* com.gec.anan.*.controller.*.*(..)) && @annotation(ananLogin)")
    public Object loginParse(ProceedingJoinPoint proceedingJoinPoint, AnanLogin ananLogin) throws Throwable {
        //获取请求对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取token
        String token = request.getHeader("token");
        //判断token
        if(!StringUtils.hasText(token)){
            throw new AnanException(ResultCodeEnum.LOGIN_AUTH);
        }
        //从redis获取token
        String customerId = (String) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        if(StringUtils.hasText(customerId)){
            AuthContextHolder.setUserId(Long.parseLong(customerId));
        }
        //返回
        return proceedingJoinPoint.proceed();
    }
}
